package com.jpcc.vw.onlineRadio.activity;

import android.Manifest;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Popup;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.cns.android.atmospherelamp.AtmosphereLampManager;
import com.google.gson.Gson;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.query.In;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.adapter.PlayHistoryAdapter;
import com.jpcc.vw.onlineRadio.application.MusicApplication;
import com.jpcc.vw.onlineRadio.base.BaseActivity;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.db.DatabaseHelperOrm;
import com.jpcc.vw.onlineRadio.db.DownloadTrackDbBean;
import com.jpcc.vw.onlineRadio.http.HttpClient;
import com.jpcc.vw.onlineRadio.model.IRadio;
import com.jpcc.vw.onlineRadio.model.action.DeletePlayHistoryAction;
import com.jpcc.vw.onlineRadio.model.action.DownloadTrackAction;
import com.jpcc.vw.onlineRadio.model.action.DownloadTrackAction2;
import com.jpcc.vw.onlineRadio.model.action.WaveAction;
import com.jpcc.vw.onlineRadio.model.bean.AlbumBrowseBean;
import com.jpcc.vw.onlineRadio.model.bean.Announcer;
import com.jpcc.vw.onlineRadio.model.bean.BaseBean;
import com.jpcc.vw.onlineRadio.model.bean.DeletePlayHistoryEntity;
import com.jpcc.vw.onlineRadio.model.bean.LiveRadioDetailBean;
import com.jpcc.vw.onlineRadio.model.bean.PlayHistoryEntity;
import com.jpcc.vw.onlineRadio.model.bean.PlayHistoryOnlineBean;
import com.jpcc.vw.onlineRadio.model.bean.PlayHistoryOnlineEntity;
import com.jpcc.vw.onlineRadio.model.bean.RadioDeailBean;
import com.jpcc.vw.onlineRadio.model.bean.RadioSumBean;
import com.jpcc.vw.onlineRadio.model.bean.RecentAlbumRadioTrackBean;
import com.jpcc.vw.onlineRadio.model.bean.SubordinatedAlbum;
import com.jpcc.vw.onlineRadio.model.bean.Track;
import com.jpcc.vw.onlineRadio.model.impl.RadioImpl;
import com.jpcc.vw.onlineRadio.service.AlbumRadioAudioPlayer;
import com.jpcc.vw.onlineRadio.utils.CommonSubscriber;
import com.jpcc.vw.onlineRadio.utils.PermissionReq;
import com.jpcc.vw.onlineRadio.utils.ProcessInfoUtils;
import com.jpcc.vw.onlineRadio.utils.SyncHisUtils;
import com.jpcc.vw.onlineRadio.utils.SyncHistoryUtils;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.jpcc.vw.onlineRadio.utils.TrackUtils;
import com.lzy.okhttpserver.download.DownloadInfo;
import com.lzy.okhttpserver.download.DownloadManager;
import com.lzy.okhttpserver.listener.DownloadListener;
import com.orhanobut.logger.Logger;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action0;
import rx.functions.ActionN;
import rx.functions.Func2;

/**
 * 播放历史activity
 */
public class PlayHistoryActivity extends BaseActivity {

    private List<RecentAlbumRadioTrackBean> results = new ArrayList<>();
    private PlayHistoryAdapter adapter;
    private DatabaseHelperOrm helper;
    private DownloadManager downloadManager;
    private MaterialDialog progressDialog;


    @BindView(R.id.listview_history)
    ListView listview_history;
    @BindView(R.id.layout_back)
    RelativeLayout layout_back;
    @BindView(R.id.layout_search)
    RelativeLayout layout_search;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_delete_all)
    TextView tv_delete_all;
    @BindView(R.id.tv_show_empty)
    TextView tv_show_empty;
    @BindView(R.id.layout_deleteAll)
    RelativeLayout layout_deleteAll;
    @BindView(R.id.imv_top_bottom_line)
    ImageView imv_top_bottom_line;
    @BindView(R.id.progress_circular)
    ProgressBar progress_circular;
    @BindView(R.id.imv_new_search)
    ImageView imv_new_search;
    private IRadio model;
    private BroadcastReceiver deleteHisReceiver;

    @Override
    public int getLayoutId() {
        return R.layout.activity_play_history;
    }


    @Override
    public void showProgress() {
        progressDialog.show();
    }

    @Override
    public void hideProgress() {
        progressDialog.dismiss();
    }

    @Override
    public void initProgressDialog() {

        progressDialog = new MaterialDialog.Builder(this)
                .progress(true, 0)
                .content(getResources().getString(R.string.string_102))
                .autoDismiss(false)
                .cancelable(false)
                .build();

    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        layout_search.setVisibility(View.INVISIBLE);
        imv_new_search.setVisibility(View.INVISIBLE);
        adapter = new PlayHistoryAdapter(results, this);
        tv_title.setText(getResources().getString(R.string.string_24));
        listview_history.setAdapter(adapter);
        helper = DatabaseHelperOrm.getHelper(this);
        tv_show_empty.setVisibility(View.GONE);
//        SyncHisUtils.doSyncHistory();
        deleteHisReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null) {
                    Bundle bundle = intent.getExtras();
                    if (bundle != null) {
                        String action = bundle.getString("action");
                        if ("DeleteSpecificHistory".equals(action)) {
                            DeletePlayHistoryAction event = new DeletePlayHistoryAction();
                            event.setContentType(bundle.getInt("ContentType"));
                            event.setAlbumId(bundle.getLong("AlbumId"));
                            event.setTrackId(bundle.getLong("TrackId"));
                            EventBus.getDefault().post(event);
                        } else if ("DeleteAllHistory".equals(action)) {
                            ClearAllHis();
                        }
                    }
                }
            }
        };
        IntentFilter deleteHisFilter = new IntentFilter("com.jpcc.vw.PlayHistoryActivity");
        this.registerReceiver(deleteHisReceiver, deleteHisFilter);
        prepareData();
//        EventBus.getDefault().register(this);
        layout_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PlayHistoryActivity.this.finish();
            }
        });
        layout_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PlayHistoryActivity.this, SearchActivity.class);
                startActivity(intent);
            }
        });

        layout_deleteAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (results == null || results.size() == 0) {
                    ToastUtils.show(R.string.string_60);
                } else {
                    if (!Constants.isRelease) {
                        MaterialDialog dialog = new MaterialDialog.Builder(PlayHistoryActivity.this).title(PlayHistoryActivity.this.getResources().getString(R.string.string_30)).content(PlayHistoryActivity.this.getResources().getString(R.string.string_92)).positiveText(PlayHistoryActivity.this.getResources().getString(R.string.string_32)).negativeText(PlayHistoryActivity.this.getResources().getString(R.string.string_33)).onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                ClearAllHis();
                            }
                        }).build();
                        dialog.show();
                    } else {
                        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                        Intent setAlertIntent = new Intent("com.jpcc.vw.PlayHistoryActivity");
                        setAlertIntent.putExtra("action", "DeleteAllHistory");
                        PendingIntent pendingIntent = PendingIntent.getBroadcast(PlayHistoryActivity.this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                        Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_92));
                        popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
                        popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
                        notificationManager.addPopup(0x0006, popup);
                    }
                }
            }
        });

        listview_history.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RecentAlbumRadioTrackBean clickItem = results.get(position);
                if (model == null) {
                    model = new RadioImpl();
                }
                if ("album".equals(clickItem.getType())) {
                    getAlbumDetail(clickItem.getAlbumId(), clickItem.getTrackId(), clickItem);
                } else {
                    getLiveingRadioProgramDetail(clickItem.getAlbumId(), clickItem.getAlbumName());
                }
            }
        });
    }

    private void ClearAllHis() {
        if (model == null) {
            model = new RadioImpl();
        }
        DeleteBuilder deleteBuilder = null;
        try {
            deleteBuilder = helper.getRecentDao().deleteBuilder();
            deleteBuilder.where().eq("userId", MusicApplication.GetUserId());
            deleteBuilder.delete();
            prepareData();
        } catch (SQLException e) {
            e.printStackTrace();
        }





//        model.getPlayHistory().subscribe(new CommonSubscriber<PlayHistoryOnlineBean>() {
//            @Override
//            public void onSuccess(PlayHistoryOnlineBean response) {
//                List<DeletePlayHistoryEntity> deletes = new ArrayList<>();
//                for (PlayHistoryOnlineEntity onlineEntity : response.getData()) {
//                    DeletePlayHistoryEntity historyEntity = new DeletePlayHistoryEntity();
//                    historyEntity.setContentType(onlineEntity.getContentType());
//                    if (onlineEntity.getContentType() == 1) {
//                        historyEntity.setAlbumId(onlineEntity.getAlbum().getId());
//                        historyEntity.setTrackId(onlineEntity.getTrack().getId());
//                    } else {
//                        historyEntity.setRadioId(onlineEntity.getRadio().getId());
//                        if (onlineEntity.getProgram() != null) {
//                            historyEntity.setScheduleId(onlineEntity.getProgram().getId());
//                        }
//                    }
//                    historyEntity.setDeletedAt(new Date().getTime());
//                    deletes.add(historyEntity);
//                }
//                HttpClient.DeletePlayHistory(new Gson().toJson(deletes), new StringCallback() {
//                    @Override
//                    public void onError(Call call, Exception e, int id) {
//                        ToastUtils.show(getResources().getString(R.string.string_90));
//                    }
//
//                    @Override
//                    public void onResponse(String response, int id) {
//                        ToastUtils.show(getResources().getString(R.string.string_91));
//                        BaseBean result = new Gson().fromJson(response, BaseBean.class);
//                        if (result.getCode() == 0) {
//                            SyncHistoryUtils.syncHistory(PlayHistoryActivity.this, new SyncHistoryUtils.onSyncHistory() {
//                                @Override
//                                public void onSyncHistorySuccess() {
//                                    prepareData();
//                                }
//
//                                @Override
//                                public void onsyncHistoryFail() {
//
//                                }
//                            });
//                        } else {
//                            ToastUtils.show(getResources().getString(R.string.string_90));
//                        }
//                    }
//                });
//            }
//
//            @Override
//            public void onFailure(BaseBean response) {
//                ToastUtils.show(getResources().getString(R.string.string_90));
//            }
//        });
    }


    @Override
    protected void onResume() {
        super.onResume();
//        if (Constants.isRelease) {
//            ConnectivityManager connectivityManager = (ConnectivityManager) MusicApplication.GetInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
//            boolean connected = connectivityManager.getNetworkStatus();
//            Logger.i("playhistory network status-->" + connected);
//            if (!connected) {
//                ToastUtils.show(R.string.string_103);
//            } else {
//                syncPlayHistory();
//            }
//        } else {
//            syncPlayHistory();
//        }
    }

    @Override
    public void setupData() {
        if (Constants.isRelease) {
            try {
                boolean atmosphereStatus = AtmosphereLampManager.getInstance(this).isHmiAtmosphereLampOn();
                String color = AtmosphereLampManager.getInstance(this).getHmiAtmosphereLampColor();
                doAtmosphere(atmosphereStatus, color);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        this.unregisterReceiver(deleteHisReceiver);
    }


    @Override
    public void doAtmosphere(boolean rgbOn, String color) {
        Logger.i("doAtmosphere" + "rgbOn-->" + rgbOn);
        Logger.i("doAtmosphere" + "color-->" + color);
        if (rgbOn) {
            if (TextUtils.isEmpty(color)) {
                imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
            } else {
                imv_top_bottom_line.setColorFilter(Color.parseColor(color));
            }
        } else {
            imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
        }
    }

    private void getAlbumDetail(long albumId, long trackId, RecentAlbumRadioTrackBean ClickTrack) {
        model.GetAlbumBrowse(albumId, 1).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<AlbumBrowseBean>() {
            @Override
            public void onSuccess(AlbumBrowseBean response) {
                hideProgress();
                if ((response.getData().getTracks() != null) && (response.getData().getTracks().size() > 0)) {
                    List<Track> datas = new ArrayList<>();
                    datas.addAll(response.getData().getTracks());
                    for (Track track : datas) {
                        track.setVIPFree(ClickTrack.isVipFree());
                    }
                    boolean contains = false;
                    int index = -1;
                    for (Track track : datas) {
                        index = index + 1;
                        if (track.getId() == trackId) {
                            contains = true;
                            break;
                        }
                    }
                    if (contains) {
                        AlbumRadioAudioPlayer.get().setOnSources(datas, index, 4, -1);
                        try {
                            HashMap<String, Object> queryMaps = new HashMap<>();
                            queryMaps.put("userId", MusicApplication.GetUserId());
                            queryMaps.put("trackId", ClickTrack.getTrackId());
                            queryMaps.put("albumId", ClickTrack.getAlbumId());
                            RecentAlbumRadioTrackBean lastClick = helper.getRecentDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("trackId", ClickTrack.getTrackId()).and().eq("albumId", ClickTrack.getAlbumId()).queryForFirst();
                            lastClick.setTimeStamp(new Date().getTime());
                            DeleteBuilder deleteBuilder = null;
                            try {
                                deleteBuilder = helper.getRecentDao().deleteBuilder();
                                deleteBuilder.where().eq("albumId", ClickTrack.getAlbumId()).and().eq("trackId", ClickTrack.getTrackId());
                                deleteBuilder.delete();
                                helper.getRecentDao().update(lastClick);
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                            delayHandler.sendEmptyMessageDelayed(0x12, 600);
                            delayHandler.sendEmptyMessage(0x12);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Track track = new Track();
                        track.setId(trackId);


                        SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                        subordinatedAlbum.setId(ClickTrack.getAlbumId());
                        subordinatedAlbum.setAlbumTitle(ClickTrack.getAlbumName());
                        Announcer announcer = new Announcer();
                        announcer.setNickname("");
                        track.setId(trackId);
                        track.setTrackTitle(ClickTrack.getTrackName());
                        track.setCoverUrlLarge(ClickTrack.getCover());
                        track.setPlayUrl32(ClickTrack.getTrackUrl());//response.getData().getSupportBitrates().get(0).getRate24AacUrl());
                        track.setCanDownload(true);
                        track.setDownloadUrl(ClickTrack.getDownloadUrl());
                        track.type = "album";
                        track.setSubordinatedAlbum(subordinatedAlbum);
                        track.setAnnouncer(announcer);


                        datas.add(0, track);
                        AlbumRadioAudioPlayer.get().setOnSources(datas, 0, 4, -1);


                        try {
                            HashMap<String, Object> queryMaps = new HashMap<>();
                            queryMaps.put("userId", MusicApplication.GetUserId());
                            queryMaps.put("trackId", ClickTrack.getTrackId());
                            queryMaps.put("albumId", ClickTrack.getAlbumId());
                            List<RecentAlbumRadioTrackBean> lastClicks = helper.getRecentDao().queryForFieldValues(queryMaps);

                            RecentAlbumRadioTrackBean lastClick = helper.getRecentDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("trackId", ClickTrack.getTrackId()).and().eq("albumId", ClickTrack.getAlbumId()).queryForFirst();

//                            RecentAlbumRadioTrackBean lastClick = lastClicks.get(0);
                            lastClick.setTimeStamp(new Date().getTime());


                            DeleteBuilder deleteBuilder = null;
                            try {
                                deleteBuilder = helper.getRecentDao().deleteBuilder();
                                deleteBuilder.where().eq("albumId", ClickTrack.getAlbumId()).and().eq("trackId", ClickTrack.getTrackId());
                                deleteBuilder.delete();
                                helper.getRecentDao().create(lastClick);
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }


//                            prepareData();
                            delayHandler.sendEmptyMessageDelayed(0x12, 600);
                            delayHandler.sendEmptyMessage(0x12);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

            @Override
            public void onFailure(BaseBean response) {
                hideProgress();
                ToastUtils.show(response.getStatusMessage());
            }
        });
    }


    private void getLiveingRadioProgramDetail(long radioId, String radioName) {
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int weekday = c.get(Calendar.DAY_OF_WEEK);

        Observable.zip(model.GetPlayingProgramDetail(radioId), model.getLiveSchedules(radioId, weekday - 1), new Func2<LiveRadioDetailBean, RadioDeailBean, RadioSumBean>() {
            @Override
            public RadioSumBean call(LiveRadioDetailBean liveRadioDetailBean, RadioDeailBean radioDeailBean) {
                RadioSumBean response = new RadioSumBean();
                if (liveRadioDetailBean.getCode() == 0 && radioDeailBean.getCode() == 0) {
                    response.setLiveRadio(liveRadioDetailBean);
                    response.setRadioSchedule(radioDeailBean);
                    return response;
                }
                return response;
            }
        }).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new Subscriber<RadioSumBean>() {
            @Override
            public void onCompleted() {
                hideProgress();
            }

            @Override
            public void onError(Throwable e) {
                hideProgress();
            }

            @Override
            public void onNext(RadioSumBean radioSumBean) {
                hideProgress();
                List<Track> sources = new ArrayList<>();


                if (radioSumBean.getRadioSchedule() != null && radioSumBean.getRadioSchedule().getData() != null) {
                    for (RadioDeailBean.RadioSchedule schedule : radioSumBean.getRadioSchedule().getData()) {
                        if (!TextUtils.isEmpty(schedule.getListenBackUrl())) {
                            Track track = new Track();
                            SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                            subordinatedAlbum.setId(radioId);
                            subordinatedAlbum.setAlbumTitle(radioName);
                            Announcer announcer = new Announcer();
                            announcer.setNickname("");
                            track.setId(schedule.getId());
                            track.setTrackTitle(schedule.getRelatedProgram().getProgramName());
                            track.setCoverUrlLarge(schedule.getRelatedProgram().getBackPicUrl());
                            track.setPlayUrl32(schedule.getListenBackUrl());
                            track.setCanDownload(false);
                            track.setDownloadUrl("");
                            track.type = "radio";
                            track.setSubordinatedAlbum(subordinatedAlbum);
                            track.setAnnouncer(announcer);
                            track.setLive(false);


                            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                            long endInt = 0;
                            long startInt = 0;
                            try {
                                if (schedule.getEndTime().equals("00:00")) {
                                    schedule.setEndTime("24:00");
                                }
                                Date end = sdf.parse(schedule.getEndTime());
                                endInt = end.getTime();
                                Date start = sdf.parse(schedule.getStartTime());
                                startInt = start.getTime();
                                Logger.i("endtime-startTime--->" + (endInt - startInt) / 1000);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            track.setStartTime(schedule.getStartTime());
                            track.setEndString(schedule.getEndTime());
                            track.setDuration((endInt - startInt) / 1000);


                            sources.add(track);
                        }
                    }
                }


                Track liveRadio = new Track();
                if (radioSumBean.getLiveRadio() != null) {
                    LiveRadioDetailBean response = radioSumBean.getLiveRadio();
                    SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                    subordinatedAlbum.setId(radioId);
                    subordinatedAlbum.setAlbumTitle(radioName);
                    Announcer announcer = new Announcer();
                    announcer.setNickname("");
                    liveRadio.setId(response.getData().getId());
                    liveRadio.setTrackTitle(response.getData().getProgramName());
                    liveRadio.setCoverUrlLarge(response.getData().getBackPicUrl());
                    liveRadio.setPlayUrl32(response.getData().getRate24AacUrl());
                    liveRadio.setCanDownload(false);
                    liveRadio.setDownloadUrl("");
                    liveRadio.type = "radio";
                    liveRadio.setSubordinatedAlbum(subordinatedAlbum);
                    liveRadio.setAnnouncer(announcer);
                    liveRadio.setLive(true);
                }
                Constants.LastModeFlag = false;
                AlbumRadioAudioPlayer.get().setOnSourcesForRadio(sources, liveRadio, true, 0);


                RecentAlbumRadioTrackBean lastClick = null;
                try {
                    lastClick = helper.getRecentDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("albumId", radioId).queryForFirst();
                    lastClick.setTimeStamp(new Date().getTime());
                    DeleteBuilder deleteBuilder = null;
                    try {
                        deleteBuilder = helper.getRecentDao().deleteBuilder();
                        deleteBuilder.where().eq("albumId", radioId).and().eq("userId", MusicApplication.GetUserId());
                        deleteBuilder.delete();
                        helper.getRecentDao().create(lastClick);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }


                delayHandler.sendEmptyMessageDelayed(0x12, 600);
                delayHandler.sendEmptyMessage(0x12);
            }
        });
    }


    private void getLiveingProgramDetail(long radioId, String radioName) {
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int weekday = c.get(Calendar.DAY_OF_WEEK);

        Observable.zip(model.GetPlayingProgramDetail(radioId), model.getLiveSchedules(radioId, weekday - 1), new Func2<LiveRadioDetailBean, RadioDeailBean, RadioSumBean>() {
            @Override
            public RadioSumBean call(LiveRadioDetailBean liveRadioDetailBean, RadioDeailBean radioDeailBean) {
                RadioSumBean response = new RadioSumBean();
                if (liveRadioDetailBean.getCode() == 0 && radioDeailBean.getCode() == 0) {
                    response.setLiveRadio(liveRadioDetailBean);
                    response.setRadioSchedule(radioDeailBean);
                    return response;
                }
                return response;
            }
        }).subscribe(new Subscriber<RadioSumBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(RadioSumBean radioSumBean) {
                List<Track> sources = new ArrayList<>();
                if (radioSumBean.getLiveRadio() != null) {
                    LiveRadioDetailBean response = radioSumBean.getLiveRadio();
                    Track track = new Track();
                    SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                    subordinatedAlbum.setId(radioId);
                    subordinatedAlbum.setAlbumTitle(radioName);
                    Announcer announcer = new Announcer();
                    announcer.setNickname("");
                    track.setId(response.getData().getId());
                    track.setTrackTitle(response.getData().getProgramName());
                    track.setCoverUrlLarge(response.getData().getBackPicUrl());
                    track.setPlayUrl32(response.getData().getRate24AacUrl());
                    track.setCanDownload(false);
                    track.setDownloadUrl("");
                    track.type = "radio";
                    track.setSubordinatedAlbum(subordinatedAlbum);
                    track.setAnnouncer(announcer);
                    track.setLive(true);
                    sources.add(track);
                }
                Constants.LastModeFlag = false;
                AlbumRadioAudioPlayer.get().setOnSources(sources, 0, 4, -1);
                adapter.notifyDataSetChanged();


                HashMap<String, Object> queryMaps = new HashMap<>();
                queryMaps.put("userId", MusicApplication.GetUserId());
                queryMaps.put("albumId", radioId);
                List<RecentAlbumRadioTrackBean> lastClicks = null;
                RecentAlbumRadioTrackBean lastClick = null;
                try {
                    lastClicks = helper.getRecentDao().queryForFieldValues(queryMaps);
                    lastClick = lastClicks.get(0);
                    lastClick.setTimeStamp(new Date().getTime());
                } catch (SQLException e) {
                    e.printStackTrace();
                }


                DeleteBuilder deleteBuilder = null;
                try {
                    deleteBuilder = helper.getRecentDao().deleteBuilder();
                    deleteBuilder.where().eq("albumId", radioId).and().eq("userId", MusicApplication.GetUserId());
                    deleteBuilder.delete();
                    helper.getRecentDao().create(lastClick);
                } catch (SQLException e) {
                    e.printStackTrace();
                }


                prepareData();


//                HashMap<String, Object> queryMaps = new HashMap<>();
//                queryMaps.put("userId", MusicApplication.GetUserId());
////                queryMaps.put("trackId", ClickTrack.getTrackId());
//                queryMaps.put("albumId", radioId);
//                List<RecentAlbumRadioTrackBean> lastClicks = helper.getRecentDao().queryForFieldValues(queryMaps);
//                RecentAlbumRadioTrackBean lastClick = lastClicks.get(0);
//                lastClick.setTimeStamp(new Date().getTime());
//
//
//                DeleteBuilder deleteBuilder = null;
//                try {
//                    deleteBuilder = helper.getRecentDao().deleteBuilder();
//                    deleteBuilder.where().eq("albumId", ClickTrack.getAlbumId()).and().eq("trackId", ClickTrack.getTrackId());
//                    deleteBuilder.delete();
//                    helper.getRecentDao().create(lastClick);
//                } catch (SQLException e) {
//                    e.printStackTrace();
//                }
//
//
//                prepareData();
//
//
//                syncPlayHistory();

            }
        });
    }


    private Handler delayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            prepareData();
        }
    };

    private void prepareData() {
        prepareDatas();
    }


    /**
     * 新的组织数据的格式
     */
    private void prepareDatas() {
        DatabaseHelperOrm helper = DatabaseHelperOrm.getHelper(this);
        try {
            List<RecentAlbumRadioTrackBean> local_results = helper.getRecentDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).query();
            List<RecentAlbumRadioTrackBean> orderedResults = new ArrayList<>();
            List<Long> Ids = new ArrayList<>();
            if (local_results.size() > 0) {
                tv_show_empty.setVisibility(View.GONE);
                for (RecentAlbumRadioTrackBean entity : local_results) {
                    if ("radio".equals(entity.getType())) {
                        if (!Ids.contains(entity.getAlbumId())) {
                            Ids.add(entity.getAlbumId());
                            if (orderedResults.size() < 20) {
                                orderedResults.add(entity);
                            }
                        }
                    } else {
                        if(!Ids.contains(entity.getAlbumId())){
                            Ids.add(entity.getAlbumId());
                            if (orderedResults.size() < 20) {
                                orderedResults.add(entity);
                            }
                        }
                    }
                }
                results.clear();
                results.addAll(orderedResults);
            } else {
                tv_show_empty.setText(getResources().getString(R.string.string_99));
                tv_show_empty.setVisibility(View.VISIBLE);
                results.clear();
                results.addAll(orderedResults);
            }
            adapter.setDatas(results);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public void onEvent(DownloadTrackAction action) {
        if (TextUtils.isEmpty(action.getDir()) || TextUtils.isEmpty(action.getFileName()) || action.getTrack() == null) {
            Logger.i("not null");
            return;
        }
        Logger.i("not null");
        PermissionReq.with(this).permissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).result(new PermissionReq.Result() {
            @Override
            public void onGranted() {
                Logger.i("onGranted()");
                RecentAlbumRadioTrackBean result = action.getTrack2();
                String path = action.getDir() + action.getFileName();
                ToastUtils.show(R.string.string_49);
                OkHttpUtils
                        .get()
                        .url(result.getDownloadUrl())
                        .build().execute(new FileCallBack(TrackUtils.getTrackDir(), "" + result.getAlbumId() + result.getTrackId() + "." + result.getDownloadUrl().substring(result.getDownloadUrl().length() - 3, result.getDownloadUrl().length())) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtils.show(R.string.string_27);
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        ToastUtils.show(R.string.string_61);
                        DownloadTrackDbBean info = new DownloadTrackDbBean();
                        info.setUserId(MusicApplication.GetUserId());
                        info.setAlbumId(result.getAlbumId());
                        info.setCover(result.getCover());
                        info.setAlbumName(result.getAlbumName());
                        info.setAuthor(result.getAuthor());
                        info.setTrackId(result.getTrackId());
                        info.setTrackName(result.getTrackName());
                        info.setTrackUrl(TrackUtils.getTrackDir() + action.getFileName());
                        info.setTimeStamp(new Date().getTime());
                        info.setDuration(result.getDuration());
                        info.setAlbumIntro("");
                        try {
                            DownloadTrackDbBean resultQuery = DatabaseHelperOrm.getHelper(PlayHistoryActivity.this).getDownloadDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("albumId", info.getAlbumId()).and().eq("trackId", info.getTrackId()).queryForFirst();
                            if (resultQuery != null) {
                                resultQuery.setTimeStamp(new Date().getTime());
                                DatabaseHelperOrm.getHelper(PlayHistoryActivity.this).getDownloadDao().update(resultQuery);
                            } else {
                                DatabaseHelperOrm.getHelper(PlayHistoryActivity.this).getDownloadDao().create(info);
                            }
                            ToastUtils.show(R.string.string_28);
                        } catch (SQLException e) {
                            ToastUtils.show(R.string.string_27);
                            e.printStackTrace();
                        }
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {

                    }
                });
            }

            @Override
            public void onDenied() {
                ToastUtils.show(R.string.string_37);
            }
        }).request();
    }


    public void onEvent(DeletePlayHistoryAction action) {
//        DeletePlayHistoryEntity historyEntity = new DeletePlayHistoryEntity();
//        historyEntity.setContentType(action.getContentType());
//        if (action.getContentType() == 1) {
//            historyEntity.setAlbumId(action.getAlbumId());
//            historyEntity.setTrackId(action.getTrackId());
//        } else {
//            historyEntity.setRadioId(action.getAlbumId());
//            historyEntity.setScheduleId(action.getTrackId());
//        }
//        historyEntity.setDeletedAt(new Date().getTime());
//        List<DeletePlayHistoryEntity> deletes = new ArrayList<>();
//        deletes.add(historyEntity);
//        HttpClient.DeletePlayHistory(new Gson().toJson(deletes), new StringCallback() {
//            @Override
//            public void onError(Call call, Exception e, int id) {
//            }
//
//            @Override
//            public void onResponse(String response, int id) {
//                Logger.i(response.toString());
//                BaseBean result = new Gson().fromJson(response, BaseBean.class);
//                if (result.getCode() == 0) {
//                    DeleteBuilder deleteBuilder = null;
//                    try {
//                        deleteBuilder = helper.getRecentDao().deleteBuilder();
//                        deleteBuilder.where().eq("albumId", action.getAlbumId());
//                        deleteBuilder.delete();
//                        prepareData();
//                    } catch (SQLException e) {
//                        e.printStackTrace();
//                    }
//
//
//                }
//            }
//        });



        DeleteBuilder deleteBuilder = null;
        try {
            deleteBuilder = helper.getRecentDao().deleteBuilder();
            deleteBuilder.where().eq("albumId", action.getAlbumId());
            deleteBuilder.delete();
            prepareData();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }


    private void syncPlayHistory() {
        tv_show_empty.setVisibility(View.GONE);
        List<PlayHistoryEntity> history = new ArrayList<>();
        try {
            List<RecentAlbumRadioTrackBean> local_results = helper.getRecentDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).query();
            for (RecentAlbumRadioTrackBean recent : local_results) {
                if (history.size() > 20) {
                    break;
                }
                PlayHistoryEntity entity = new PlayHistoryEntity();
                if ("album".equals(recent.getType())) {
                    entity.setContentType(1);
                    entity.setAlbumId(recent.getAlbumId());
                    entity.setTrackId(recent.getTrackId());
                    entity.setAlbumTitle(recent.getAlbumName());
                    entity.setTrackTitle(recent.getTrackName());
                    entity.setPlayBeginAt(recent.getTimeStamp());
                    if (recent.getCurrentDuration() / 1000 == 0) {
                        entity.setPlayedSecs(1);
                    } else {
                        entity.setPlayedSecs(recent.getCurrentDuration() / 1000);
                    }
                    entity.setPlayEndAt(entity.getPlayBeginAt() + entity.getPlayedSecs() * 1000);
                    entity.setTrackCoverUrlLarge(recent.getCover());
                } else {
                    entity.setContentType(2);
                    entity.setRadioId(recent.getAlbumId());
                    entity.setScheduleId(recent.getTrackId());
                    entity.setRadioName(recent.getAlbumName());
                    entity.setProgramName(recent.getTrackName());
                    entity.setPlayBeginAt(recent.getTimeStamp());
                    if (recent.getCurrentDuration() / 1000 == 0) {
                        entity.setPlayedSecs(1);
                    } else {
                        entity.setPlayedSecs(recent.getCurrentDuration() / 1000);
                    }
                    entity.setPlayEndAt(entity.getPlayBeginAt() + entity.getPlayedSecs() * 1000);
                    entity.setRadioCoverUrlLarge(recent.getCover());
                }
                history.add(entity);
            }
            if (history.size() > 0) {
//                showProgress();
                progress_circular.setVisibility(View.VISIBLE);
                showProgress();
                HttpClient.SyncPlayHistory(new Gson().toJson(history), new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
//                        Logger.i(e.toString());
//                        hideProgress();
                        progress_circular.setVisibility(View.INVISIBLE);
                        hideProgress();
                        ToastUtils.show(R.string.string_105);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Logger.i(response.toString());
//                        hideProgress();
                        progress_circular.setVisibility(View.INVISIBLE);
                        BaseBean resBean = new Gson().fromJson(response, BaseBean.class);
//                    if (Constants.STATUS_SUCCESS_CODE != resBean.getCode()&&(resBean.getCode()!=520082&&resBean.getCode()!=100001)) {
//                        ToastUtils.show(R.string.string_105);
//                        return;
//                    }
                        SyncHistoryUtils.syncHistory(PlayHistoryActivity.this, new SyncHistoryUtils.onSyncHistory() {
                            @Override
                            public void onSyncHistorySuccess() {
                                prepareData();
                                hideProgress();
                                progress_circular.setVisibility(View.INVISIBLE);
                            }

                            @Override
                            public void onsyncHistoryFail() {
                                hideProgress();
                                progress_circular.setVisibility(View.INVISIBLE);
                            }
                        });
                    }
                });
            } else {
                progress_circular.setVisibility(View.VISIBLE);
                showProgress();
                SyncHistoryUtils.syncHistory(PlayHistoryActivity.this, new SyncHistoryUtils.onSyncHistory() {
                    @Override
                    public void onSyncHistorySuccess() {
                        prepareData();
                        hideProgress();
                        progress_circular.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onsyncHistoryFail() {
                        hideProgress();
                        progress_circular.setVisibility(View.INVISIBLE);
                    }
                });
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    private void deletePlayHistory() {
        DeletePlayHistoryEntity historyEntity = new DeletePlayHistoryEntity();
        historyEntity.setContentType(1);
        historyEntity.setAlbumId(18533898);
        historyEntity.setTrackId(125762334);
        historyEntity.setDeletedAt(new Date().getTime());
        List<DeletePlayHistoryEntity> deletes = new ArrayList<>();
        deletes.add(historyEntity);
        HttpClient.DeletePlayHistory(new Gson().toJson(deletes), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
//                Logger.i(e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                Logger.i(response.toString());
            }
        });
    }


    public void onEvent(WaveAction action) {
//        adapter.notifyDataSetChanged();
    }


    public void onEvent(DownloadTrackAction2 action) {
        Logger.i("onGranted()");
        Track result = action.getTrack();
        String path = action.getDir() + action.getFileName();
        if (downloadManager == null) {
            downloadManager = DownloadManager.getInstance(PlayHistoryActivity.this);
        }

        downloadManager.addTaskWithName(result.getDownloadUrl(), new DownloadListener() {
            @Override
            public void onProgress(DownloadInfo downloadInfo) {
                //adapter.notifyDataSetChanged();
            }

            @Override
            public void onFinish(DownloadInfo downloadInfo) {
                adapter.notifyDataSetChanged();
                DownloadTrackDbBean info = new DownloadTrackDbBean();
                info.setUserId(MusicApplication.GetUserId());
                info.setAlbumId(result.getSubordinatedAlbum().getId());
                info.setCover(result.getSubordinatedAlbum().getCoverUrlLarge());
                info.setAlbumName(result.getSubordinatedAlbum().getAlbumTitle());
                info.setAuthor(result.getAnnouncer().getNickname());
                info.setTrackId(result.getId());
                info.setTrackName(result.getTrackTitle());
                info.setTrackUrl(TrackUtils.getTrackDir() + action.getFileName());
                info.setTimeStamp(new Date().getTime());
                info.setDuration(result.getDuration() * 1000);
                info.setAlbumIntro(result.getTrackIntro());
                try {
                    DownloadTrackDbBean resultQuery = DatabaseHelperOrm.getHelper(PlayHistoryActivity.this).getDownloadDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("albumId", info.getAlbumId()).and().eq("trackId", info.getTrackId()).queryForFirst();
                    if (resultQuery != null) {
                        resultQuery.setTimeStamp(new Date().getTime());
                        DatabaseHelperOrm.getHelper(PlayHistoryActivity.this).getDownloadDao().update(resultQuery);
                    } else {
                        DatabaseHelperOrm.getHelper(PlayHistoryActivity.this).getDownloadDao().create(info);
                    }
                    ToastUtils.show(R.string.string_28);
                } catch (SQLException e) {
                    ToastUtils.show(R.string.string_27);
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(DownloadInfo downloadInfo, String errorMsg, Exception e) {

            }

            @Override
            public void onAdd(DownloadInfo downloadInfo) {
                super.onAdd(downloadInfo);
                ToastUtils.show(R.string.string_49);
                adapter.notifyDataSetChanged();
            }
        }, true, action.getFileName());


    }
}
